package sale

import (
	"time"
	"github.com/astaxie/beego/validation"
	"dhfshop/controllers/base"
	"dhfshop/models/sale"
)

type SkuTypeController struct {
	base.BaseController
}

func (this *SkuTypeController) Post() {
	var v sale.SkuType
	valid := validation.Validation{}
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := this.Ctx.Input.GetData("curUserId").(int)
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	if len(v.ItemId) < 1 {
	    this.ServeError("item_id is invalid")
		return
	}
	id, err := sale.AddSkuType(&v)
	if err != nil {
        this.ServeError(err.Error())
		return
    }
	r := struct {
		    Id     int64       `json:"id"`
	        Added  time.Time   `json:"added"`
	    }{Id:id, Added:time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}


func (this *SkuTypeController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := sale.GetAllSkuTypes(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
		r := struct {
		    TotalCount     int64           `json:"total_count"`
	        SkuType       []*sale.SkuType `json:"sku_types"`
	    }{TotalCount: cnt, SkuType: l}
	    this.Data["json"] = r
	this.ServeJSON()
}

func (this *SkuTypeController) Put() {
	v := sale.SkuType{}
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := this.Ctx.Input.GetData("curUserId").(int)
	valid := validation.Validation{}
	valid.Required(v.Id, "id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := sale.UpdateSkuTypeById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		    Id        int64       `json:"id"`
	        Modified  time.Time   `json:"modified"`
	    }{Id:v.Id, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *SkuTypeController) Delete() {
	//companyId := this.Ctx.Input.GetData("curCompanyId").(int)
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	id, err := this.GetInt("id")
	if err != nil {
	    this.ServeError(err.Error())
		return 
	}
	if err := sale.DeleteSkuType(int64(id)); err != nil{
		this.ServeError(err.Error())
		return
	}
	r := struct {
		    Id    int         `json:"id"`
	        Modified  time.Time   `json:"modified"`
	    }{Id:id, Modified:time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}
